package com.projet.controllers;

import com.projet.entities.Commande;
import com.projet.controllers.util.JsfUtil;
import com.projet.controllers.util.PaginationHelper;
import com.projet.entities.Details;
import com.projet.entities.Produit;
import com.projet.entities.ProduitCommande;
import com.projet.entities.Utilisateur;
import com.projet.facades.CommandeFacade;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "commandeController")
@SessionScoped
public class CommandeController implements Serializable {
    public int i=9;
    private String MotDePasse;
    public Commande commande;
    private Commande current;
    private DataModel items = null; 
    private Details details;
    private Produit produit;
    private ProduitCommande produitCommande;
    @ManagedProperty(value = "#{produitController}")
    private ProduitController produitController;

    public void setProduitController(ProduitController produitController) {
        this.produitController = produitController;
    }
     public ProduitController getProduitController() {
       
        return this.produitController;
    }
    @ManagedProperty(value = "#{utilisateurController}")
    private UtilisateurController utilisateurController;

    public void setUtilisateurController(UtilisateurController utilisateurController) {
        this.utilisateurController = utilisateurController;
    }
    public UtilisateurController getUtilisateurController() {
       
        return this.utilisateurController;
    } 
    @ManagedProperty(value = "#{produitCommandeController}")
    private ProduitCommandeController produitCommandeController;

    public void setProduitCommandeController(ProduitCommandeController produitCommandeController) {
        this.produitCommandeController = produitCommandeController;
    }
    public ProduitCommandeController getProduitCommandeController() {
       
        return this.produitCommandeController;
    }   
    @ManagedProperty(value = "#{detailsController}")
    private DetailsController detailsController;

    public void setDetailsController(DetailsController detailsController) {
        this.detailsController = detailsController;
    }
    public DetailsController getDetailsController() {
       
        return this.detailsController;
    }
    @EJB
    private com.projet.facades.CommandeFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    public CommandeController() {
    }
    public Commande getSelected() {
        if (current == null) {
            current = new Commande();
            selectedItemIndex = -1;
        }
        return current;
    }
    private CommandeFacade getFacade() {
        return ejbFacade;
    }
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }
    public String prepareList() {
        recreateModel();
        return "List";
    }
    public String prepareView() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Commande();
        selectedItemIndex = -1;
        return "Create";
    }
    public String create() {
        try {  
            current.setMotDePasse(getUtilisateurController().getSelected().getMotDePasse());
            i++;
            String s=String.valueOf(i);
            current.setMtDPasse(current.getMotDePasse());            
            current.setIdCommande(s);
            details=new Details();
            produitCommande=new ProduitCommande();
            details.setIdCommandeIdProduit(s);
            detailsController.setcurrent(details);
            detailsController.create();
           // produit=produitController.find();
            produitCommande.setDetails(details);
            produitCommande.setCommande(current);
            //produitCommande.setProduit(produit);
            //produitCommandeController.setcurrent(produitCommande);
            //produitCommandeController.create();
            current.setDatePaiement(current.getDateLivraison());
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Ajout effectué avec succés");
            return prepareCreate();  
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage("error");
            return null;
        }
    }
    public String listcommande(){
        return null;
        
    }
    public String prepareEdit() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Commande) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CommandeDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Commande.class)
    public static class CommandeControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CommandeController controller = (CommandeController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "commandeController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Commande) {
                Commande o = (Commande) object;
                return getStringKey(o.getIdCommande());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Commande.class.getName());
            }
        }
    }
}
